//
//  canyujxViewController.m
//  gpos_app
//
//  Created by apple on 2018/8/21.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "canyujxViewController.h"
#import "Masonry.h"
#import "ForgetPassWordViewController.h"
#import "GPosAPI.h"
#import "WKProgressHUD.h"
#import "XMRegisterViewController.h"
#import "SVProgressHUD.h"

#define NUM @"0123456789."
#define ALPHA @"0123456789"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789."

@interface canyujxViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UITextField * onemimaTixeField;
@property (nonatomic,strong)UITextField * twomimaTixeField;
@property(strong,nonatomic)WKProgressHUD *hud;
@property (nonatomic,strong)UIButton * yanjingButton;
@property (nonatomic,strong)UIButton * querenButton;

@end

@implementation canyujxViewController
//改变状态栏
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    //隐藏返回提示文字
//    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.title = @"竞选";
    self.navigationItem.title=@"竞选";

    [self loadDataView];
}

- (void)loadDataView{
    UIImageView * topImage = [[UIImageView alloc] init];
    topImage.image = [UIImage imageNamed:@"icon_cyjingxuan"];
    [self.view addSubview:topImage];
    [topImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(kNavbarHeight+50);
        make.centerX.equalTo(self.view);
    }];
    
    UILabel * jxjeLabel = [[UILabel alloc] init];
    jxjeLabel.text = @"竞选金额";
    jxjeLabel.textColor = [UIColor blackColor];
    jxjeLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:jxjeLabel];
    
    [jxjeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topImage.mas_bottom).with.offset(70);
        make.left.equalTo(self.view).with.offset(25);
        //        make.width.equalTo(@60);
    }];
    
    UILabel * danweiLabel = [[UILabel alloc] init];
    danweiLabel.text = @"GPOS";
    danweiLabel.textColor = [UIColor blackColor];
    danweiLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:danweiLabel];
    
    [danweiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(jxjeLabel);
        make.right.equalTo(self.view).with.offset(-25);
        //        make.width.equalTo(@60);
    }];
    
    self.onemimaTixeField = [[UITextField alloc] init];
    self.onemimaTixeField.placeholder =@"请输入参与竞选的金额";
    self.onemimaTixeField.keyboardType=UIKeyboardTypeDecimalPad;
    self.onemimaTixeField.font = [UIFont systemFontOfSize:14.f];
    //    self.onemimaTixeField.secureTextEntry = YES;
    self.onemimaTixeField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.onemimaTixeField];
    [self.onemimaTixeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(jxjeLabel);
        make.left.equalTo(jxjeLabel.mas_right).with.offset(20);
        make.width.equalTo(@160);
    }];
    
    UIView * oneView = [[UIView alloc] init];
    oneView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:oneView];
    [oneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(jxjeLabel.mas_bottom).with.offset(5);
        make.left.equalTo(self.view).with.offset(25);
        make.right.equalTo(self.view).with.offset(-25);
        make.height.equalTo(@1);
    }];
    
    UILabel * jymimaLabel = [[UILabel alloc] init];
    jymimaLabel.text = @"交易密码";
    jymimaLabel.textColor = [UIColor blackColor];
    jymimaLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:jymimaLabel];
    
    [jymimaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(oneView.mas_bottom).with.offset(25);
        make.left.equalTo(self.view).with.offset(25);
        //        make.width.equalTo(@60);
    }];
    
    UIButton * wjmimaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [wjmimaButton setTitle:@"忘记密码 ?" forState:UIControlStateNormal];
    wjmimaButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [wjmimaButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.view addSubview:wjmimaButton];
    [wjmimaButton addTarget:self action:@selector(wjmimaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [wjmimaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(jymimaLabel);
        make.right.equalTo(self.view).with.offset(-25);
        make.width.equalTo(@70);
    }];
    
    self.yanjingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.yanjingButton];
    [self.yanjingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(jymimaLabel);
        make.right.equalTo(wjmimaButton.mas_left).with.offset(-10);
        
    }];
    [self.yanjingButton setImage:[UIImage imageNamed:@"icon_biyan_l"] forState:UIControlStateNormal];
    [self.yanjingButton addTarget:self action:@selector(jymimaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.twomimaTixeField = [[UITextField alloc] init];
    self.twomimaTixeField.placeholder =@"请输入交易密码";
    self.twomimaTixeField.keyboardType=UIKeyboardTypeNumberPad;
    self.twomimaTixeField.font = [UIFont systemFontOfSize:14.f];
    self.twomimaTixeField.secureTextEntry = YES;
    self.twomimaTixeField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:self.twomimaTixeField];
    [self.twomimaTixeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(jymimaLabel);
        make.left.equalTo(jymimaLabel.mas_right).with.offset(20);
        make.width.equalTo(@130);
    }];
    
    UIView * twoView = [[UIView alloc] init];
    twoView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:twoView];
    [twoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(jymimaLabel.mas_bottom).with.offset(5);
        make.left.equalTo(self.view).with.offset(25);
        make.right.equalTo(self.view).with.offset(-25);
        make.height.equalTo(@1);
    }];
    
    self.querenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.querenButton setBackgroundImage:[UIImage imageNamed:@"icon_anniu_f"] forState:UIControlStateNormal];
    [self.querenButton setTitle:@"参与竞选" forState:UIControlStateNormal];
    [self.querenButton addTarget:self action:@selector(querenButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.querenButton];
    
    
    [self.querenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view).with.offset(-20);
        make.top.equalTo(twoView.mas_bottom).with.offset(30);
    }];
    
    UILabel * cankaozhiaLabel = [[UILabel alloc] init];
    cankaozhiaLabel.text = @"*上榜参考值2000 GPOS";
    cankaozhiaLabel.textColor = [UIColor grayColor];
    cankaozhiaLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:cankaozhiaLabel];
    
    [cankaozhiaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.querenButton.mas_bottom).with.offset(0);
        make.left.equalTo(self.view).with.offset(20);
        //        make.width.equalTo(@60);
    }];
    
    self.onemimaTixeField.delegate = self;
    self.twomimaTixeField.delegate = self;
}


//忘记密码wjmimaButtonAction
- (void)wjmimaButtonAction:(UIButton *)sender {
    
    ForgetPassWordViewController * forgitPassWordVC = [[ForgetPassWordViewController alloc] init];
    [self.navigationController pushViewController:forgitPassWordVC animated:YES];
    
    
}

//参与竞选按钮
- (void)querenButtonAction:(UIButton *)sender {
    
    if (self.onemimaTixeField.text.length==0) {
        self.hud=[WKProgressHUD popMessage:@"请输入竞选金额" inView:self.view duration:1 animated:YES];
        return;
    }
    if (self.twomimaTixeField.text.length==0) {
        self.hud=[WKProgressHUD popMessage:@"请输入交易密码" inView:self.view duration:1 animated:YES];
        return;
    }
    if (self.twomimaTixeField.text.length!=6) {
        self.hud=[WKProgressHUD popMessage:@"密码不正确" inView:self.view duration:1 animated:YES];
        return;
    }
//    if (self.onemimaTixeField.text.length) {
//        self.hud=[WKProgressHUD popMessage:@"无竞选资格" inView:self.view duration:1 animated:YES];
//        return;
//    }
    
    int str = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSDictionary * params = @{@"userId" :@(str),
                              @"amount" :self.onemimaTixeField.text,
                              @"password" : self.twomimaTixeField.text
                              };
    self.querenButton.userInteractionEnabled=NO;
    [GPosAPI requestCampaignWithParams:params andCallback:^(id obj) {
        NSLog(@"---%@",obj);
        
        if (obj==nil) {
            self.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
            self.querenButton.userInteractionEnabled=YES;
        }else{
            
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                self.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];
                NSNotification *LoseResponse = [NSNotification notificationWithName:@"buttonLoseRespon" object:nil];
                
                //                    2.发送通知:
                [[NSNotificationCenter defaultCenter] postNotification:LoseResponse];

                [self.navigationController popViewControllerAnimated:YES];
                self.querenButton.userInteractionEnabled=YES;
                
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402){
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                self.querenButton.userInteractionEnabled=YES;
                
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else{
                
                self.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];
                self.querenButton.userInteractionEnabled=YES;
            }
            
            
        }
        
    }];
    
}

//隐藏密码
- (void)jymimaButtonAction:(UIButton *)sender {
    
    if (self.twomimaTixeField.secureTextEntry == YES) {
        
        self.twomimaTixeField.secureTextEntry = NO;
        [self.yanjingButton setImage:[UIImage imageNamed:@"icon_yangjingl"] forState:UIControlStateNormal];
    }else {
        self.twomimaTixeField.secureTextEntry = YES;
        [self.yanjingButton setImage:[UIImage imageNamed:@"icon_biyan_l"] forState:UIControlStateNormal];
        
    }
    
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.twomimaTixeField ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.twomimaTixeField.text.length >= 6) {
            self.twomimaTixeField.text = [textField.text substringToIndex:6];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    if (textField == self.onemimaTixeField ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.onemimaTixeField.text.length >= 10) {
            self.onemimaTixeField.text = [textField.text substringToIndex:10];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        if ([string isEqualToString:@"."] && ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""])) {
            return NO;
        }
        
        NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
        [str insertString:string atIndex:range.location];
        if (str.length >= [str rangeOfString:@"."].location+6){
            return NO;
        }
        
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed=YES;
    }
    return self;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
